﻿using System;
using System.Net;
using System.Net.Sockets;
using QFramework;

namespace HKTools
{
    public class CMD_UDP_MulticastMsg : AbstractCommand
    {
        string msg;
        string multicastAddress;
        int multicastPort;

        public CMD_UDP_MulticastMsg(string msg, string multicastAddress, int multicastPort = 0)
        {
            this.msg = msg;
            this.multicastAddress = multicastAddress;
            this.multicastPort = multicastPort;
        }

        protected override void OnExecute()
        {
            try
            {
                // 解析多播地址
                IPAddress ipAddress = IPAddress.Parse(multicastAddress);

                // 校验是否为 IPv4 多播地址（D类地址：224.0.0.0 ~ 239.255.255.255）
                if (ipAddress.AddressFamily != AddressFamily.InterNetwork)
                {
                    HKDebug.LogError("仅支持 IPv4 多播地址！");
                    return;
                }

                byte[] bytes = ipAddress.GetAddressBytes();
                if (bytes[0] < 224 || bytes[0] > 239)
                {
                    HKDebug.LogError($"地址 {multicastAddress} 不是合法的 IPv4 多播地址（需为 224.0.0.0 ~ 239.255.255.255）");
                    return;
                }

                // 判断传入的端口是否合法
                if (multicastPort < 0 || multicastPort > 65535)
                {
                    HKDebug.LogError("端口号必须在 0 ~ 65535 之间！");
                    return;
                }

                if (multicastPort != 0)
                    this.GetSystem<IHK_UdpSystem>().MulticastMsg(msg, ipAddress, multicastPort);
                else
                    this.GetSystem<IHK_UdpSystem>().MulticastMsg(msg, ipAddress);
            }
            catch (FormatException)
            {
                HKDebug.LogError($"地址 {multicastAddress} 格式错误，无法解析为有效 IP 地址！");
            }
        }
    }
}